import type { MenuTreeResult } from "@/api/types";
import type { UseBaseTable } from "@/composables";
import { ElMessage } from "element-plus";
import { menuApi } from "@/api";
import { useBaseTable } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";

interface UseMenuTable extends Omit<UseBaseTable<MenuTreeResult>, "tablePage"> {
    /** 获取数据 */
    fetchTableData: () => void;
    /** 删除菜单或权限 */
    handleRecordDelete: (id: string, menuType: string | undefined) => void;
}

/** 菜单树表格逻辑 */
export function useMenuTable(): UseMenuTable {
    const { tableData, tableLoading } = useBaseTable<MenuTreeResult>();

    /** 获取菜单树 */
    function fetchTableData(): void {
        tableLoading.value = true;
        apiCall(
            () => menuApi.listMenuTree(),
            (data) => {
                tableData.value = data;
            },
            {
                onFinally: () => {
                    tableLoading.value = false;
                },
            },
        );
    }

    /** 删除菜单或权限 */
    function handleRecordDelete(id: string, menuType: string | undefined): void {
        apiCall(
            () => {
                if (menuType === "button") {
                    return menuApi.removePermission(id);
                }
                // undefined 默认是 菜单类型
                return menuApi.removeMenu(id);
            },
            () => {
                ElMessage.success($t("resp.deleteSuccess"));
                fetchTableData();
            },
        );
    }

    return {
        tableLoading,
        tableData,
        fetchTableData,
        handleRecordDelete,
    };
}
